<template>
  <div>
    <el-dialog
      title="添加维修记录"
      :visible.sync="visible"
      width="650px"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <u-form
        ref="uFormRef"
        label-width='134px'
        v-model="form"
        :defaultForm="defaultForm"
        :formArray="formArray"
        @submit="onsubmit"
        @close="visible = false"
        mode="form"
        v-loading="loading"
      >
        <template #deviceId="scope">
            <div class="form-item-wrap">
              <el-input
                placeholder="请输入设备ID或者点击选择设备按钮"
                v-model="form[scope.row.key]"
                style="flex: 1;"
                clearable
                @change="checkDeviceIdValid"
              >
              </el-input>
              <el-button
                v-show="!deviceData || !deviceData.deviceId"
                icon="el-icon-search"
                type="primary"
                style="margin-left: 10px;"
                @click="showSelectDeviceView">选择设备</el-button>
            </div>
        </template>

        <template #workOrderId="scope">
          <el-select
            v-model="form.workOrderId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入工单ID"
            :remote-method="getWorkOrder"
            :loading="loading"
            style="width: 100%;"
            clearable
          >
            <el-option
              v-for="item in workOrdersList"
              :key="item.id"
              :label="item.id"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </u-form>
    </el-dialog>

    <select-device-dialog
      v-model="selectDeviceDialogVisible"
      @select="handleSelectDevice"
    />
  </div>
</template>
<script>
import UForm from '@/components/uForm'
import {getWorkOrderList} from "@/api/operationAndMonitoring/workOrder";
import {getModelListByDeviceId, listManager} from "@/api/device/placeManager";
import SelectDeviceDialog from "@/views/operationAndMonitoring/workerOrder/components/SelectDeviceDialog";
import {addMaitenance} from '@/api/operationAndMonitoring/fixRecords'
export default {
  name: "AddFixRecordsDialog",
  components: {UForm, SelectDeviceDialog},
  props: {
    value: {
      type: Boolean,
      default: false
    },
    deviceData: {
      type: Object
    }
  },
  data() {
    return {
      form: {},
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {
        deviceId: '',
        workOrderId: '',
        moduleName: '',
        moduleCode: '',
        maintenanceType: '',
        oldModule: '',
        newModule: '',
        operationUserCode: '',
        operationUserName: '',
        remark: ''
      },
      formArray: [
        {
          label: "所属设备", key: "deviceId", col: 24, slot: "deviceId",
          rule: {required: true, message: '所属设备不能为空！', trigger: 'change'},
        },
        {
          label: "关联工单", key: "workOrderId", col: 24, slot: 'workOrderId',
          rule: {required: true, message: '关联工单不能为空！', trigger: 'blur'},
        },
        {
          label: "维修模块", key: "moduleCode", col: 24, type: "select", options: [],
          rule: {required: true, message: '维修模块不能为空！', trigger: 'blur'},
        },
        {
          label: "维修方式", key: "maintenanceType", col: 24, type: "select",
          rule: {required: true, message: "维修方式不能为空！", trigger: 'blur'},
        },
        {
          label: "旧模块品牌型号", key: "oldModule", col: 24, type: "input",
        },
        {
          label: "新模块品牌型号", key: "newModule", col: 24, type: "input",
        },
        {
          label: "维修人员", key: "operationUserCode", col: 24, type: "select",
          rule: {required: true, message: '维修人员不能为空！', trigger: 'blur'},
        },
        {label: "备注：", key: "remark", col: 24, type: "textarea",},
      ],
      loading: false,
      selectDeviceDialogVisible: false,
      workOrdersList: [],
      maintenanceTypeOptions: [
        {label: '更换', value: 1},
        {label: '维修', value: 2},
      ],
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        return this.$emit('input', val)
      }
    },
    // 运维人员下拉框数据
    operationUserOptions() {
      return this.$store.state.device.operationUserOptions || []
    },
  },
  methods: {
    /** 根据工单id查询是否存在工单 */
    getWorkOrder(id) {
      this.loading = true;
      getWorkOrderList({
        deviceId: this.form.deviceId,
        id
      }).then(response => {
          this.workOrdersList = response.rows;
          this.loading = false;
        }
      )
    },
    /** 查询设备模块列表 */
    getModelList(deviceId) {
      this.loading = true;
      getModelListByDeviceId({deviceId}).then(response => {
          const _data = response.rows || [];
          this.formArray.find(item => item.key === 'moduleCode').options = _data.map(item => {
            return {
              label: item.modelName,
              value: item.modelCode,
            }
          });
          this.loading = false;
        }
      ).catch(error => {
        console.log(error, '获取模块失败')
      })
    },
    // 选择设备列表弹窗 选择设备回调
    handleSelectDevice(deviceInfo) {
      this.form.deviceId = deviceInfo.deviceId;
      this.getModelList(deviceInfo.deviceId)
    },
    showSelectDeviceView() {
      this.selectDeviceDialogVisible = true
    },
    /** 查询该ID在设备部署管理列表是否存在*/
    checkDeviceIdValid(id) {
      this.loading = true;
      this.isValidDeviceId = false;
      // 请求参数
      const params = {
        deviceId: this.form.deviceId
      };
      listManager(params).then(response => {
          const list = response.rows;
          if (list.length) {
            this.isValidDeviceId = true;
            this.form.deploymentName = list[0].deploymentName
            this.form.deploymentCode = list[0].deploymentCode
            this.getModelList(list[0].deviceId)
          } else {
            this.$modal.confirmAlert('该设备ID不存在已部署设备列表，请重新输入！')
          }
        }
      ).finally(() => {
        this.loading = false;
      })
    },
    // 回填表单
    fillDeviceIdAndGetModel() {
      this.form.deviceId = this.deviceData.deviceId;
      this.getModelList(this.deviceData.deviceId)
    },
    // 添加文件上传成功、删除图片时都会被调用
    imageUploadChange(imgUrl) {
      this.form.image = imgUrl
    },
    onsubmit(callBack) {
      this.loading = true;
      // 获取模块名称
      const moduleList = this.formArray.find(item => item.key === 'moduleCode').options;
      const moduleItem = moduleList.find(item => item.value === this.form.moduleCode);
      if(moduleItem) this.form.moduleName = moduleItem.label;
      // 获取维修人员名称
      const operation = this.operationUserOptions.find(item => item.value === this.form.operationUserCode);
      if(operation) this.form.operationUserName = operation.label;

      addMaitenance(this.form).then((response) => {
        this.visible = false;
        this.$emit('getList')
        this.$modal.msgSuccess("添加成功");
      }).finally(() => {
        callBack && callBack()
        this.loading = false;
      });
    }
  },
  watch: {
    operationUserOptions:{
      immediate: true,
      handler(newValue){
        // 设置运维人员选项数据
        try {
          this.formArray.find(item => item.key === 'operationUserCode').options = newValue;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      }
    },
    value: {
      handler(newValue) {
        if (newValue) {
          // 清空选项
          this.workOrdersList = [];
          this.formArray.find(item => item.key === 'moduleCode').options = [];
          this.form = JSON.parse(JSON.stringify(this.defaultForm));
          if(this.deviceData) this.fillDeviceIdAndGetModel();
        }else {
          this.$refs.uFormRef.reset();
        }
      }
    }
  },
  created() {
    // 设置维修类型选项数据
    try {
      this.formArray.find(item => item.key === 'maintenanceType').options = this.maintenanceTypeOptions;
    } catch (e) {
      console.log("找不到对应表单项", e)
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}
</style>
